<template>
  <!-- 与树节点显示一致的组件 -->
  <div class="v-editor-models-tree-select-node-label g-jc-sb">
    <!-- {{row.value}} -->
    <div
      v-if="mode === 'horizontal'"
      class="horizontal"
    >
      <div
        v-for="(item, index) of valueData"
        :key="index"
        class="value-item"
        @click="handleClickItem(item)"
      >
        <img
          style="margin-right: 4px; height: 16px"
          :src="item.icon"
        />
        <NodeLabel
          :nodeData="item"
          :selected="false"
          :disabled="false"
          :show-new="false"
          @contextmenu="propertyModelContextMenu($event, item)"
        />
      </div>

      <div
        v-if="selected && !row.readonly && !specialModelDisabled && !isModelDisabled && !tableElementDisabled"
        class="add-btn"
      >
        <img
          src="statics/icons/app/iconmore.png"
          class="g-pointer"
          @click="handleAdd"
        />
      </div>
    </div>

    <div
      v-else
      class="g-flex-1 _list_scroll"
    >
      <div
        v-for="(item, index) of valueData"
        :key="index"
        :class="{ _selected: selected && selectedModelId === item.id }"
        class="g-pd-l-8 g-one-line"
        @click="handleClickItem(item)"
        @contextmenu="propertyModelContextMenu($event, item)"
      >
        <span>
          <img
            style="margin-right: 4px; height: 16px"
            :src="item.icon"
          />
          <NodeLabel
            :nodeData="item"
            :selected="false"
            :disabled="false"
            :show-new="false"
          />
        </span>
      </div>
    </div>

    <div
      v-if="selected && !row.readonly && !specialModelDisabled && !isModelDisabled && mode !== 'horizontal'"
      style="border-left: 1px solid #ddd; line-height: 14px"
      class="g-pd-4 g-flex-0"
    >
      <div>
        <img
          src="statics/icons/app/iconadd.png"
          class="g-pointer"
          @click="handleAdd"
        />
      </div>
      <div class="g-m-t-4">
        <img
          src="statics/icons/app/iconreduce.png"
          class="g-pointer"
          :class="{ _disable: valueData.length == 0 || (row.nullable === false && valueData.length == 1) }"
          @click="handleRemove"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { actionManager } from "@/action/ActionManager";
import { CreatePropertyModelTreeSelect } from "@/modules/model/actions/project/CreatePropertyModelTreeSelect";
import { PropertyRow, ModelValue } from "../../types";
import { ref, Ref, computed, watch, inject } from "vue";
import { BusEvent, PropertyKey } from "@/constants/Enums";
import { propertyUtil } from "../../PropertyUtil";
import { modelService } from "@/modules/model/service/index";
import { StType } from "@/constants/StType";
import { modelTreeSelectWindow } from "@/modules/model/modals/modelTreeSelect";
import NodeLabel from "@/modules/model/comps/station/sider/modelTree/modelTree/NodeLabel.vue";
import { NodeData } from "@/modules/model/project/IGraphNode";
import { propertyModelContextMenu } from "../propertyUtil";
import { ActionKey } from "@/action/ActionKey";
import { locale } from "@/util/locale";

const isModelDisabled = inject("isModelDisabled", ref(false)) as Ref<boolean>;

/**
 * 模型多选-树选择弹窗
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  tableElementDisabled?: boolean;
  mode?: string; // 新增横向horizontal模式, 以便在一行内显示内容
}>();

// const projectId = app.activeProject?.id as string;
const valueData = ref<NodeData[]>([]);
watch(
  () => props.row,
  async () => {
    let rowValue: NodeData[] = [];
    if (props.row.value && Array.isArray(props.row.value)) {
      rowValue = props.row.value as NodeData[];
    } else if (props.row.value instanceof Object) {
      rowValue = [props.row.value] as NodeData[];
    }

    valueData.value = rowValue;
  },
  { immediate: true }
);

const specialModelDisabled = computed(() => {
  const specalPropertyKey = new Set([PropertyKey["Element_ownedElement"]]);
  return specalPropertyKey.has(props.row.key as PropertyKey);
});

const selectedModelId = ref("");

watch(
  () => props.selected,
  val => {
    if (val === false) {
      selectedModelId.value = "";
    }
  }
);

const handleAdd = async () => {
  const projectId = app.activeProject?.id;
  if (!projectId) return;
  const row = props.row;
  if (props.mode === "horizontal" && row.key === PropertyKey.DiagramTable_scope) {
    const model = await modelService.getModelData(projectId, row.modelId);
    const sts = model.baseSt;
    if (
      sts === StType["TableAndMatrix::CustomizeTable::BlackBoxICDTable"] ||
      sts === StType["TableAndMatrix::CustomizeTable::PartICDTable"]
    ) {
      handleDiagramTableScopeSingleSelect(row);
      return;
    }
  } else if (row.key == PropertyKey.LegendItem_specificElements) {
    // 图例相关：如果图例项存在匹配条件，提示用户
    const legendItemCondition = (await modelService.getPropertyValueById(
      projectId,
      row.modelId,
      PropertyKey.LegendItem_condition
    )) as string[];
    if (legendItemCondition?.length) {
      const res = await app.$confirm.popup({
        title: "提示",
        subTitle: locale.t("该图例项已设置匹配条件"),
        content: locale.t("设置指定元素将覆盖已设置的匹配条件，是否继续？"),
        status: "warn",
        cancelText: locale.t("button.no"),
        okText: locale.t("button.yes")
      });
      if (res.type == "cancel") return;
    }
  }

  const action = actionManager.getAction(ActionKey.CreatePropertyModelTreeSelect) as CreatePropertyModelTreeSelect;

  action?.run(props.row);
};

// 部分图表的范围属性要弹单选框
const handleDiagramTableScopeSingleSelect = (
  row: PropertyRow,
  attrTip = "radio",
  title = "属性设置",
  loadMethod = "getPropertyTreeList"
) => {
  const value = row.value as ModelValue[];
  const selectedId = value[0] ? value[0].id : "";
  modelTreeSelectWindow
    .popup({
      loadMethod: loadMethod,
      loadParams: JSON.stringify({
        row: { ...row },
        projectId: app.activeProject!.config.id
      }),
      selectedId,
      attrTip,
      title
    })
    .then(async res => {
      if (!res.success) return;
      const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(row, app.activeProject!.config.id);
      dto.value = res.selectedId;
      const result = await modelService.updateModelProperty(dto);
      if (result.code === 1000) {
        app.$bus.emit(BusEvent.REFRESH_PROPERTY, row.modelId, row.key);
      }
    });
};

function handleRemove() {
  if (!selectedModelId.value) {
    app.$notify({
      title: "提示",
      type: "error",
      message: "请选中元素再操作移除"
    });
    return;
  }
  if (props.row.specificComponent === PropertyKey.SimulationConfig_UI) {
    propertyUtil.deletePropertyAndRefresh(props.row, selectedModelId.value);
  } else {
    propertyUtil.removePropertyAndRefresh(props.row, selectedModelId.value);
  }
}

function handleClickItem(item: NodeData) {
  selectedModelId.value = item.id;
}
</script>
<style lang="scss">
@import "@/assets/css/theme.scss";
.v-editor-models-tree-select-node-label {
  // height: 100%;
  ._disable {
    cursor: not-allowed;
    color: #c1c5cb;
    filter: grayscale(100);
  }
  ._selected {
    background-color: $theme-color;
    color: #fff;
    ._name-label {
      color: #fff;
    }
  }
  ._list_scroll {
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
  }
  .horizontal {
    height: 24px;
    width: 100%;
    padding-right: 30px;
    padding-left: 11px;
    position: relative;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 24px;
    .value-item {
      display: inline-block;
      height: 16px;
      margin-right: 10px;
      line-height: 16px;
      img {
        margin-right: 6px;
        line-height: 16px;
        vertical-align: middle;
      }
      span {
        line-height: 14px;
        vertical-align: middle;
      }
    }
    .add-btn {
      line-height: 1;
      position: absolute;
      top: 50%;
      right: 5px;
      transform: translateY(-50%);
    }
  }
}
</style>
